﻿using System.Collections.Generic;
using MvcStarterKit.Core.Interfaces;
using NHibernate;
using NHibernate.Criterion;

namespace MvcStarterKit.Infrastructure
{
	public abstract class RepositoryBase<T> : IRepository<T>
	{
		public static ISession GetSession()
		{
			return (new SessionCache()).GetSession();
		}

		public virtual IList<T> GetAll()
		{
			return DetachedCriteria.For<T>().GetExecutableCriteria(GetSession()).List<T>();
		}

		public virtual void DeleteAll()
		{
			var session = GetSession();

			var transaction = session.BeginTransaction();
			var list = DetachedCriteria.For<T>()
				.GetExecutableCriteria(session)
				.List<T>();

			foreach (var item in list)
			{
				session.Delete(item);
			}

			transaction.Commit();
		}

		public virtual void Save(T entity)
		{
			GetSession().SaveOrUpdate(entity);
		}


		public T Get(object id)
		{
			return GetSession().Get<T>(id);
		}


		public void Delete(T entity)
		{
			GetSession().Delete(entity);
		}


		public void Refresh(T entity)
		{
			GetSession().Refresh(entity);
		}


		public void Flush()
		{
			GetSession().Flush();
		}
	}
}
